//定义外部模块
define('jquery', function(){
	return $;
});

//requirejs 配置
require.config({
	baseUrl : '/static',
	paths : {
		'jqueryui' : 'vendor/jquery-ui/jquery-ui',
		'backbone' : 'vendor/backbone/backbone',
		'underscore' : 'vendor/backbone/underscore',
		'semantic' : 'vendor/semantic/js/semantic',
		'upload' : 'vendor/uploadify/jquery.uploadify',
		'qtip' : 'vendor/qtip2/jquery.qtip.min',
		'highcharts' : 'vendor/highcharts/highcharts',
		'highcharts-3d' : 'vendor/highcharts/highcharts-3d',
		'global' : 'javascript/gusi',
		'text' : 'vendor/requirejs/text',
		'i18n' : 'vendor/requirejs/i18n',
		'util' : 'javascript/common/util',
		'soundmanager': 'vendor/soundmanager2/script/soundmanager2-jsmin',
		'page-player': 'vendor/soundmanager2/page-player/script/page-player',
		
		'Table': 'view/table.view',
		'table.controller': 'view/table.controller'
	},
	shim : {
		'underscore' : {
			exports : '_'
		},
		'backbone' : {
			deps : [ 'underscore', 'jquery' ],
			exports : 'Backbone'
		},
		'semantic' : {
			deps : [ 'jquery' ]
		},
		'global' : {
			deps : [ 'semantic' ]
		},
		'page-player' : {
			deps : [ 'soundmanager' ]
		}
		
	},
	config : {
		i18n : {
			locale : 'zh-cn'
		}
	}
});


require([ 'util', 'backbone', 'semantic', 'jqueryui', 'global', 'qtip' ], function(util) {
	//调用api时如果session过期返回401，则提示跳转到登录页
	_.extend(Backbone.Model.prototype, {
		initialize: function(){
			this.on('error', function(model, resp, options){
				if(resp.status == 401){
					if(window.confirm('登录超时，是否重新登录？')){
						window.location.href = '/login';
					}
				}
			});
		}
	});
	
	//给所有ajax添加请求头部信息
	$.ajaxSetup({
		beforeSend : function(request) {
			request.setRequestHeader("Request-Type", "json");
		}
	});
	
	//日期控件显示文字
	$.datepicker.setDefaults({
		dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
		monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '八月', '九月', '十月', '十一月', '十二月']
	});
	
	$(function() {
		
		//---- 定义Model-------开始 ------
		var orgType = new Backbone.Collection([ {
			"value" : "区域",
			"ordinal" : 3
		}, {
			"value" : "门店",
			"ordinal" : 6
		}, {
			"value" : "分行",
			"ordinal" : 9
		} ]);
		var Organization = Backbone.Model.extend({
			urlRoot : '/organizations',
			parse : function(response) {
				return response.organization;
			}
		});
		var Organizations = Backbone.Model.extend({
			url : '/organizations',
			defaults: {
				key: ''
			}
		});
		var Employee = Backbone.Model.extend({
			urlRoot : '/employees',
			parse : function(response) {
				return response.user;
			}
		});
		var AllEmployees = Backbone.Model.extend({
			url : '/employees/json/queryAllEmployee'
		});
		var Employees = Backbone.Model.extend({
			url : '/employees',
			defaults: {
				key: ''
			}
		});
		var Enterprises = Backbone.Model.extend({
			url : '/enterprises',
			defaults: {
				key: ''
			}
		});
		var Advers = Backbone.Model.extend({
			url : '/advers',
			defaults: {
				key: '',
				assigned: false,
				isAdmin: userCode == 10000,
				company: {}
			}
		});
		var Medias = Backbone.Model.extend({
			url : '/medias',
			defaults: {
				key: ''
			}
		});
		var Media = Backbone.Model.extend({
			urlRoot : '/medias',
			parse : function(response) {
				return response.media;
			}
		});
		var Records = Backbone.Model.extend({
			url : '/records',
			defaults: {
				key: '',
				orgId: '',
				orgName: '',
				beginTime: '',
				endTime: '',
				mediaId: ''
			}
		});
		//---- 定义Model-------结束 ------
		
		//通用的view配置，用于被其他view继承
		var globalSettings = {
			goToPage : function(e) {
				var pageNo = $(e.target).attr('data-pageNo');
				this.model.set('pageNo', pageNo);
				this.search();
			},
			switchPage: function(){
				var pageNo = $('#pageNo', this.$el).val(),
					totalPage = this.model.get('totalPage');
				if(!/^\d+$/.test(pageNo) || pageNo > totalPage){
					Fail('请输入正确的页码');
					return;
				}
				this.model.set('pageNo', pageNo);
				var self = this;
				this.model.fetch({
					data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo'),
					success: function(){
						self.model.trigger('update');
					}
				});
			},
			render : function() {
				var that = this;
				var deps = [];
				if (this.controller) {
					if (_.isArray(this.controller)) {
						$.each(this.controller, function(i, o) {
							deps.push(o);
						});
					} else {
						deps.push(this.controller);
					}
				}
				require([ 'text!/static/tmpl/' + this.template ], function(tmpl) {
					that.tmpl = _.template(tmpl);
					if (_.isFunction(that.postRender)) {
						that.postRender(that);
						Loading.close();
					}
					that.initControl();
					if (deps.length > 0) {
						require(deps, function(ctr) {
							ctr.init(that);
						});
					}
				});
				return this;
			},
			initControl : function() {
				$('.ui.checkbox').checkbox();
				$('.ui.accordion').accordion();
				$('.ui.dropdown').dropdown();
			}
		};

		var HomeView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'home',
			template : 'home.tpl',
			postRender : function() {
				var now = new Date(), that = this;
				$(that.el).html(that.tmpl({
					userName : userName,
					companyName : companyName,
					amOrPm : util.getAmOrPm(now),
					time : util.formatDate(now, 'yyyy年MM月dd日 hh时mm分ss秒')
				}));
				setTimeout(function(){
					if($('#time').length > 0){
						that.render();
					}
				}, 1000);
			}
		}, globalSettings));
		var ChangePwdView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'changePwd',
			template : 'account/password.html',
			controller : 'javascript/account/password',
			postRender : function() {
				$(this.el).html(this.tmpl());
			}
		}, globalSettings));

		var OrgListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'orgList',
			template : 'organization/list.html',
			events : {
				'click .pagination .item[data-pageNo]' : 'goToPage',
				'click .js_go': 'switchPage',
				'keydown #key': 'search'
			},
			search: function(e){
				this.model.set('key', this.$el.find('#key').val());
				if(!e || !e.keyCode || e.keyCode == 13){
					Loading.show();
					this.model.fetch({
						data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo')
					});
				}
				if(e && e.keyCode == 13){
					e.preventDefault();
				}
			},
			initialize : function() {
				Loading.show();
				this.$el.off();
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
				Loading.close();
			}
		}, globalSettings));
		var EnterListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'enterList',
			template : 'enterprise/list.html',
			initialize : function() {
				Loading.show();
				this.$el.off();
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
				Loading.close();
			}
		}, globalSettings));

		var AssignMediaView = Backbone.View.extend($.extend({
			el : '#assignMediaContainer',
			template : 'adver/assign_media.html',
			type: 'media',
			title: '配置媒体',
			postRender : function() {
				var that = this;
				$(this.el).html(this.tmpl(this.model));
				this.$el.dialog({
					autoOpen : false,
					title : that.title,
					width : 450,
					modal : true,
					close : function(){
						
					},
					buttons : [ {
						text : "提交修改",
						click : function() {
							$.ajax({
								type: 'post',
								url: '/advers/' + that.model.adver.id + '/bind/' + that.type,
								data: that.$el.find('form').serialize(),
								success: function(response){
									var form = that.$el.find('form');
									if(response.status == 'fail'){
										form.addClass('error');
										form.find('.error.message').text(response.message);
										form.find('.success.message').addClass('hidden');
									}else if(response.status == 'ok'){
										form.removeClass('error');
										form.find('.bind').removeClass('hidden');
										setTimeout(function(){
											that.$el.dialog('close');
											that.model.parentView.trigger('reRender');
										}, 1000);
									}
								}
							});
						},
						class : 'cgreen'
					},{
						text : "取消",
						click : function() {
							$(this).dialog("close");
						}
					},{
						text : "解除配对",
						click : function() {
							$.ajax({
								type: 'post',
								url: '/advers/' + that.model.adver.id + '/unbind/' + that.type,
								data: that.$el.find('form').serialize(),
								success: function(response){
									var form = that.$el.find('form');
									if(response.status == 'fail'){
										form.addClass('error');
										form.find('.error.message').text(response.message);
										form.find('.success.message').addClass('hidden');
									}else if(response.status == 'ok'){
										form.removeClass('error');
										form.find('.unbind').removeClass('hidden');
										setTimeout(function(){
											that.$el.dialog('close');
											that.model.parentView.trigger('reRender');
										}, 1000);
									}
								}
							});
						},
						class : 'cred'
					} ]
				});
				this.$el.dialog("open");
			}
		}, globalSettings));
		var AssignEmpView = AssignMediaView.extend({
			el : '#assignEmpContainer',
			template : 'adver/assign_emp.html',
			type: 'user',
			title: '配置员工',
			controller: 'javascript/adver/assign'
		});
		var BatchAssignMediaView = AssignMediaView.extend({
			el : '#batchAssignMediaContainer',
			template : 'adver/batch_assign_media.html',
			type: 'media',
			title: '批量配置媒体'
		});
		var BatchAssignEmpView = AssignMediaView.extend({
			el : '#batchAssignEmpContainer',
			template : 'adver/batch_assign_emp.html',
			type: 'user',
			title: '批量配置员工',
			controller: 'javascript/adver/assign'
		});
		var AdverListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'adverList',
			template : 'adver/list.html',
			events : {
				'click .pagination .item[data-pageNo]' : 'goToPage',
				'click .media.item' : 'showSettingMediaPage',
				'click .employee.item' : 'showSettingEmpPage',
				'click .delete.item' : 'deleteAdver',
				'click .js_batch_emp' : 'showBatchEmpPage',
				'click .js_batch_media' : 'showBatchMediaPage',
				'click .js_batch_delete' : 'batchDelete',
				'keydown #key': 'search',
				'click .js_go': 'switchPage'
			},
			controller: 'javascript/adver/list',
			initialize : function() {
				Loading.show();
				this.$el.off();
				this.model.set('isAdmin', userCode == 10000);
				this.model.on('sync', this.render, this);
				this.on('prepared', this.render, this);
				this.on('reRender', function(){
					this.model.fetch({
						data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo')
					});
				}, this);
			},
			postRender : function() {
				this.model.set('key', this.$el.find('#key').val());
				this.model.set('assigned', this.$el.find("#status").is(':checked'));
				$(this.el).html(this.tmpl(this.model.toJSON()));
				Loading.close();
			},
			search: function(e){
				if(!e || !e.keyCode || e.keyCode == 13){
					Loading.show();
					this.model.fetch({
						data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo')
					});
				}
				if(e && e.keyCode == 13){
					e.preventDefault();
				}
			},
			showSettingMediaPage : function(e) {
				var adverId = $(e.target).attr('data-value'),
					self = this;
				var adver = _.find(this.model.get('adverList'), function(adver) {
					return adver.id == adverId;
				});
				var mediaList = new Medias();
				mediaList.on('sync', function() {
					(new AssignMediaView({
						model : {
							parentView: self,
							adver : adver,
							mediaList : mediaList.get('mediaList')
						}
					})).render();
				});
				mediaList.fetch();
			},
			showSettingEmpPage : function(e) {
				var adverId = $(e.target).attr('data-value'),
					self = this;
				var adver = _.find(this.model.get('adverList'), function(adver) {
					return adver.id == adverId;
				});
				var empList = new AllEmployees();
				empList.on('sync', function() {
					(new AssignEmpView({
						model : {
							parentView: self,
							adver : adver,
							empList : empList.get('userList')
						}
					})).render();
				});
				empList.fetch();
			},
			showBatchEmpPage: function(){
				var adverIds = [],
					self = this;
				_.each($('input.adverlist:checked[value]'), function(ele){
					adverIds.push($(ele).val());
				});
				if(adverIds.length == 0){
					Fail('请至少选择一条记录');
					return;
				}
				var empList = new AllEmployees();
				empList.on('sync', function() {
					(new BatchAssignEmpView({
						model : {
							parentView: self,
							adver : {
								id: adverIds.join('_')
							},
							empList : empList.get('userList')
						}
					})).render();
				});
				empList.fetch();
			},
			showBatchMediaPage: function(){
				var adverIds = [],
					self = this;
				_.each($('input.adverlist:checked[value]'), function(ele){
					adverIds.push($(ele).val());
				});
				if(adverIds.length == 0){
					Fail('请至少选择一条记录');
					return;
				}
				var mediaList = new Medias();
				mediaList.on('sync', function() {
					(new BatchAssignMediaView({
						model : {
							parentView: self,
							adver : {
								id: adverIds.join('_')
							},
							mediaList : mediaList.get('mediaList')
						}
					})).render();
				});
				mediaList.fetch();
			},
			deleteAdver: function(e){
				var self = this;
				Confirm('删除记录', '是否删除该广告号码？', function(){
					Loading.show();
					$.post('/advers/' + $(e.target).attr('data-value') + '/delete', function(data){
						Loading.hide();
						if(data.status == 'ok'){
							self.search();
						}else{
							Fail(data.message);
							self.search();
						}
					});
				});
			},
			batchDelete: function(){
				var adverIds = [],
				self = this;
				_.each($('input.adverlist:checked[value]'), function(ele){
					adverIds.push($(ele).val());
				});
				if(adverIds.length == 0){
					Fail('请至少选择一条记录');
					return;
				}
				Confirm('批量删除', '是否批量删除广告号码？', function(){
					Loading.show();
					$.post('/advers/' + adverIds.join('_') + '/delete', function(data){
						Loading.hide();
						if(data.status == 'ok'){
							self.search();
						}else{
							Fail(data.message);
						}
					});
				});
			}
		}, globalSettings));
		var RecordListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'recordList',
			template : 'record/list.html',
			controller : 'javascript/record/list',
			events : {
				'click .pagination .item[data-pageNo]' : 'goToPage',
				'click .js_go': 'switchPage',
				'click .gusi.play.icon' : 'play',
				'click .gusi.pause.icon' : 'pause',
				'click .search' : 'search',
				'keydown #key': 'search'
			},
			initialize : function() {
				Loading.show();
				this.$el.off();
				var mediaList = new Medias();
				var recordList = new Records();
				var mediasReady = $.Deferred(), recordsReady = $.Deferred();
				this.model = recordList;
				mediaList.fetch();
				recordList.fetch();
				mediaList.on('sync', function() {
					this.model.set('mediaList', mediaList.get('mediaList'));
					mediasReady.resolve();
				}, this);
				recordList.on('sync', function() {
					recordsReady.resolve();
				}, this);
				recordList.on('update', this.render, this);
				$.when(mediasReady, recordsReady).done($.proxy(this.render, this));
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
				this.$el.find('audio').off('ended').on('ended', this.played);
				Loading.close();
			},
			play : function(e) {
				$(e.target).siblings('audio')[0].play();
				$(e.target).addClass('hide');
				$(e.target).siblings('.pause').removeClass('hide');
			},
			pause : function(e) {
				$(e.target).siblings('audio')[0].pause();
				$(e.target).addClass('hide');
				$(e.target).siblings('.play').removeClass('hide');
			},
			played : function(e) {
				$(e.target).siblings('.pause').addClass('hide');
				$(e.target).siblings('.play').removeClass('hide');
			},
			search: function(e){
				if(!e || !e.keyCode || e.keyCode == 13){
					Loading.show();
					var that = this;
					this.model.set('key', $('#key').val());
					this.model.set('orgId', $('#orgId').val());
					this.model.set('orgName', $('#orgName').val());
					this.model.set('beginTime', $('#beginTime').val());
					this.model.set('endTime', $('#endTime').val());
					this.model.set('mediaId', $('#mediaId').val());
					this.model.fetch({
						data: that.$el.find('form').serialize() + '&pageNo=' + that.model.get('pageNo'),
						success: function(){
							that.model.trigger('update');
						}
					});
				}
				if(e && e.keyCode == 13){
					e.preventDefault();
				}
			}
		}, globalSettings));
		var UploadView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'uoloadForm',
			template : 'adver/upload.html',
			controller : [ 'javascript/adver/upload', 'upload' ],
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var MediaListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'mediaList',
			template : 'media/list.html',
			events: {
				'keydown #key': 'search'
			},
			search: function(e){
				this.model.set('key', this.$el.find('#key').val());
				if(!e || !e.keyCode || e.keyCode == 13){
					Loading.show();
					this.model.fetch({
						data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo')
					});
				}
				if(e && e.keyCode == 13){
					e.preventDefault();
				}
			},
			initialize : function() {
				Loading.show();
				this.$el.off();
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
				Loading.close();
			}
		}, globalSettings));
		var OrgDetailView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'orgDetail',
			template : 'organization/detail.html',
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var EmpDetailView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'empDetail',
			template : 'employee/detail.html',
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var OrgEditView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'orgEdit',
			controller : 'javascript/organization/edit',
			template : 'organization/edit.html',
			initialize : function() {
				this.on('prepared', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var EmpEditView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'empEdit',
			controller : 'javascript/employee/edit',
			template : 'employee/edit.html',
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var MediaEditView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'mediaEdit',
			controller : 'javascript/media/edit',
			template : 'media/edit.html',
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));
		var EmpListView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'empList',
			template : 'employee/list.html',
			events : {
				'click .pagination .item[data-pageNo]' : 'goToPage',
				'click .js_go': 'switchPage',
				'keydown #key': 'search',
				'click .js_leave': 'leave'
			},
			search: function(e){
				this.model.set('key', this.$el.find('#key').val());
				if(!e || !e.keyCode || e.keyCode == 13){
					Loading.show();
					this.model.fetch({
						data: this.$el.find('form').serialize() + '&pageNo=' + this.model.get('pageNo')
					});
				}
				if(e && e.keyCode == 13){
					e.preventDefault();
				}
			},
			leave: function(e){
				var self = this;
				require(['text!/static/tmpl/employee/leave.html'], function(leaveTemplate){
					var html = _.template(leaveTemplate, {});
					console.log(html);
					$('#leave').html(html);
					$('#leaveTime').datepicker({
						dateFormat : 'yy-mm-dd'
					});
					var dialog = $('#leave', this.$el).dialog({
						autoOpen : false,
						title : '员工离职',
						width : 450,
						modal : true,
						close : function(){
							
						},
						buttons : [ {
							text : "离职",
							click : function() {
								var that = this;
								Confirm('离职确认','是否要让该员工离职？',function(){
									$.ajax({
										type: 'post',
										url: '/employees/' + $(e.target).attr('data-value') + '/leave',
										data: $('#leaveForm', that).serialize(),
										success: function(response){
											var form = $('#leaveForm', that);
											if(response.status == 'fail'){
												form.addClass('error');
												form.find('.error.message').text(response.message);
												form.find('.success.message').addClass('hidden');
											}else if(response.status == 'ok'){
												form.removeClass('error');
												form.find('.success.message').removeClass('hidden');
												setTimeout(function(){
													dialog.dialog('close');
													self.model.fetch();
												}, 1000);
											}
										}
									});
								});
							},
							class : 'cred'
						},{
							text : "取消",
							click : function() {
								$(this).dialog("close");
							}
						}]
					});
					$('#leave').dialog('open');
				});
			},
			initialize : function() {
				Loading.show();
				this.$el.off();
				this.model.set('isAdmin', userCode == 10000);
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
				Loading.close();
			}
		}, globalSettings));
		
		var EmpUploadView = Backbone.View.extend($.extend({
			el : '#container',
			template : 'employee/upload.html',
			controller : [ 'javascript/employee/upload', 'upload' ],
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			}
		}, globalSettings));

		var CreateOrgFormView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'addOrg',
			controller : 'javascript/organization/add',
			template : 'organization/add.html',
			postRender : function() {
				var oType = orgType.toJSON();
				if(this.model.get('org').fromOrg){
					var model = this.model;
					oType = _.filter(oType, function(type){ return type.ordinal > model.get('org').type; });
				}
				this.model.set('orgType', oType);
				$(this.el).html(this.tmpl(this.model.toJSON()));
			},
			initialize : function() {
				this.on('prepared', this.render, this);
			}
		}, globalSettings));

		var CreateEmpFormView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'addEmp',
			controller : 'javascript/employee/add',
			template : 'employee/add.html',
			postRender : function() {
				$(this.el).html(this.tmpl(this.model.toJSON()));
			},
			initialize : function() {
				this.model.on('sync', this.render, this);
			},
		}, globalSettings));

		var CreateEnterpriseFormView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'addEnterprise',
			controller : 'javascript/enterprise/add',
			template : 'enterprise/add.html',
			postRender : function() {
				$(this.el).html(this.tmpl({
					orgType : orgType.toJSON()
				}));
			},
		}, globalSettings));

		var CreateMediaFormView = Backbone.View.extend($.extend({
			el : '#container',
			className : 'addMedia',
			controller : 'javascript/media/add',
			template : 'media/add.html',
			postRender : function() {
				$(this.el).html(this.tmpl());
			},
		}, globalSettings));

		//前端路由控制
		var Workspace = Backbone.Router.extend({
			routes : {
				'' : 'goHome',
				'index' : 'goHome',
				'logout' : 'logout',

				'organization' : 'getOrgList',
				'organization/add(/:orgId)' : 'showAddOrgForm',
				'organization/:id/detail' : 'showOrgDetail',
				'organization/:id/edit' : 'editOrgDetail',

				'employee' : 'getEmpList',
				'employee/add(/:orgId)' : 'showAddEmpForm',
				'employee/:id/detail' : 'showEmpDetail',
				'employee/:id/edit' : 'editEmpDetail',
				'employee/upload' : 'showEmpUploadForm',

				'enterprise' : 'getEnterPriseList',
				'enterprise/add' : 'showAddEnterpriseForm',

				'adver' : 'getAdverList',
				'adver/upload' : 'showUploadForm',

				'media' : 'getMediaList',
				'media/add' : 'showAddMediaForm',
				'media/:id/edit' : 'editMediaDetail',

				'record' : 'getRecordList',

				'user/pwd' : 'changePwd',
				
				'download/:file': 'download',
				
				'report': 'reportIndex'

			},
			goHome : function() {
				(new HomeView()).render();
//				require(['Table'], function(T){
//					var Table = T.Table;
//					var Column = T.Column;
//					var table = new Table({
//						model: new Backbone.Collection([{name:'张三',age:18},{name:'李四',age:23}])
//					});
//					table.addColumn(new Column({
//						text: '姓名',
//						path: 'name'
//					}));
//					table.addColumn(new Column({
//						text: '年龄', 
//						path: 'age'
//					}));
//					table.render().appendTo($('#container'));
//				});
			},
			logout : function() {
				window.location.href = "/logout";
			},
			changePwd : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#user\\/pwd]').addClass('active');
				(new ChangePwdView()).render();
			},
			getOrgList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#organization]').addClass('active');
				var orgList = new Organizations();
				this.view = new OrgListView({
					model : orgList
				});
				orgList.fetch();
			},
			getEmpList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#employee]').addClass('active');
				var empList = new Employees();
				new EmpListView({
					model : empList
				});
				empList.fetch();
			},
			getEnterPriseList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#enterprise]').addClass('active');
				var enterList = new Enterprises();
				new EnterListView({
					model : enterList
				});
				enterList.fetch();
			},
			getAdverList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#adver]').addClass('active');
				var enterPriseReady = $.Deferred(), adverReady = $.Deferred();
				var adverList = new Advers();
				var enterpriseList = new Enterprises();
				enterpriseList.on('sync', function(){
					enterPriseReady.resolve();
				});
				adverList.on('sync', function(){
					adverReady.resolve();
				});
				var view = new AdverListView({
					model : adverList
				});
				$.when(enterPriseReady, adverReady).done(function(){
					adverList.set('companyList', enterpriseList.get('companyList'));
					view.trigger('prepared');
				});
				enterpriseList.fetch();
				adverList.fetch();
			},
			getRecordList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#record]').addClass('active');
				new RecordListView();
			},
			showUploadForm : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#adver]').addClass('active');
				var enterpriseList = new Enterprises();
				new UploadView({
					model : enterpriseList
				});
				enterpriseList.fetch();
			},
			showEmpUploadForm : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#adver]').addClass('active');
				var enterpriseList = new Enterprises();
				new EmpUploadView({
					model : enterpriseList
				});
				enterpriseList.fetch();
			},
			getMediaList : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#media]').addClass('active');
				var mediaList = new Medias();
				new MediaListView({
					model : mediaList
				});
				mediaList.fetch();
			},
			showOrgDetail : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#organization]').addClass('active');
				var organization = new Organization({
					id : id
				});
				new OrgDetailView({
					model : organization
				});
				organization.fetch();
			},
			editOrgDetail : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#organization]').addClass('active');
				var empReady = $.Deferred(), orgReady = $.Deferred();
				var organization = new Organization({
					id : id
				});
				var view = new OrgEditView({
					model : organization
				});
				organization.on('sync', function(){
					orgReady.resolve();
				});
				organization.fetch();
				
				var allEmpList = new AllEmployees();
				allEmpList.on('sync', function(){
					view.model.set('userList', allEmpList.get('userList'));
					empReady.resolve();
				});
				allEmpList.fetch();
				
				$.when(empReady, orgReady).done(function(){
					view.trigger('prepared');
				});
			},
			editEmpDetail : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#employee]').addClass('active');
				var employee = new Employee({
					id : id
				});
				new EmpEditView({
					model : employee
				});
				employee.fetch();
			},
			editMediaDetail : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#media]').addClass('active');
				var media = new Media({
					id : id
				});
				new MediaEditView({
					model : media
				});
				media.fetch();
			},
			showEmpDetail : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#employee]').addClass('active');
				var employee = new Employee({
					id : id
				});
				new EmpDetailView({
					model : employee
				});
				employee.fetch();
			},
			showAddOrgForm : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#organization]').addClass('active');
				var empReady = $.Deferred(), orgReady = $.Deferred();
				var view = new CreateOrgFormView({
					model: new Backbone.Model({
						defaults: {org: {}}
					})
				});
				
				var allEmpList = new AllEmployees();
				allEmpList.on('sync', function(){
					view.model.set('userList', allEmpList.get('userList'));
					empReady.resolve();
				});
				allEmpList.fetch();
				
				var org = new Organization({id: id,'fromOrg': !!id});
				org.on('sync', function(){
					view.model.set('org', org.toJSON());
					orgReady.resolve();
				});
				org.fetch();
				
				$.when(empReady, orgReady).done(function(){
					view.trigger('prepared');
				});
			},
			showAddEmpForm : function(id) {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#employee]').addClass('active');
				var org;
				if (this.view && id) {
					org = new Backbone.Model(_.find(this.view.model.get('orgList'), function(org) {
						return org.id == id;
					}));
					new CreateEmpFormView({model: org});
					org.set('fromOrg', !!id);
					org.trigger('sync');
				} else {
					org = new Organization({id: id,'fromOrg': !!id});
					new CreateEmpFormView({model: org});
					org.fetch();
				}
			},
			showAddEnterpriseForm : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#enterprise]').addClass('active');
				(new CreateEnterpriseFormView()).render();
			},
			showAddMediaForm : function() {
				$('.gusi.menu .item').removeClass('active');
				$('a.item[href=#media]').addClass('active');
				(new CreateMediaFormView()).render();
			},
			download: function(file){
				window.open('/attach/' + file);
			},
			reportIndex: function(){
				Loading.show();
				require(['/static/view/report.index.view.js'], function(ReportIndexView){
					var oType = _.filter(orgType.toJSON(), function(type){ return type.ordinal > 0; });
					var view = new ReportIndexView({
						model: {orgType: oType}
					});
					$('#container').html(view.render().$el);
					Loading.close();
				});
			}
		});
		
		//启动路由---开始---
		window.app = new Workspace();
		Backbone.history.start({
			pushState : true //html5模式
		});
		//启动路由---结束---
	});
});
